<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <a-row style="border: 1px solid #d9d9d9">
      <a-col :span="3">
        <a-tree
          ref="treeBox"
          :selected-keys="selectedValues"
          :tree-data="sortData"
          :props="defaultProps"
          style="background-color: #fff"
          :defaultSelectedKeys="defaultSelectedKeys"
          @select="treeSelect"
        />
      </a-col>
      <a-col :span="21" style="border-left: 1px solid #d9d9d9">
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24" style="margin-top: 10px;margin-left:10px">
              <a-col :xl="10" :lg="11" :md="12" :sm="24">
                <a-form-item :label="$t('时间')">
                  <a-date-picker
                    :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                    valueFormat="YYYY-MM-DD HH:mm:ss"
                    :placeholder="$t('请选择开始时间')"
                    class="query-group-cust"
                    v-model="queryParam.createTime_begin"
                  ></a-date-picker>
                  <span class="query-group-split-cust"></span>
                  <a-date-picker
                    :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                    valueFormat="YYYY-MM-DD HH:mm:ss"
                    :placeholder="$t('请选择结束时间')"
                    class="query-group-cust"
                    v-model="queryParam.createTime_end"
                  ></a-date-picker>
                </a-form-item>
              </a-col>
              <template v-if="toggleSearchStatus">
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
                  <a-form-item :label="$t('项目名称')">
                    <a-input :placeholder="$t('请输入项目名称')" v-model="queryParam.gameInfo"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :xl="6" :lg="7" :md="8" :sm="24" v-if="!tenantid">
                  <a-form-item :label="$t('门店')">
                    <a-select v-model="queryParam.shopCode">
                      <a-select-option v-for="(item,i) in shops" :key="i" :value="item.value">{{item.title}}<span v-if="item.value != ''">（{{item.value}}）</span></a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </template>
              <a-col :xl="8" :lg="9" :md="10" :sm="24">
                <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery" icon="search">{{$t('查询')}}</a-button>
                  <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{$t('重置')}}</a-button>
                  <a-dropdown>
                    <a-menu slot="overlay" @click="handleDateClick">
                      <a-menu-item key="1"> {{$t('今日')}} </a-menu-item>
                      <a-menu-item key="2"> {{$t('近三天')}} </a-menu-item>
                      <a-menu-item key="3"> {{$t('近七天')}} </a-menu-item>
                      <a-menu-item key="4"> {{$t('近一月')}} </a-menu-item>
                      <a-menu-item key="5"> {{$t('近三月')}} </a-menu-item>
                      <a-menu-item key="6"> {{$t('近半年')}} </a-menu-item>
                      <a-menu-item key="7"> {{$t('本年')}} </a-menu-item>
                    </a-menu>
                    <a-button type="primary" style="margin-left: 8px"> {{ $t('快捷查询') }} <a-icon type="down" /></a-button>
                  </a-dropdown>
                  <a @click="handleToggleSearch" style="margin-left: 8px">
                    {{ toggleSearchStatus ? $t('收起') : $t('展开') }}
                    <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                  </a>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- 查询区域-END -->
        <!-- 操作按钮区域 -->
        <div class="table-operator" style="margin-left:10px">
          <a-button type="primary" :loading="exloading" @click="handleExportXls($t('游戏机台运营报表'))" v-has="'BisGameCoinRecordController:export'">{{$t('导出')}}</a-button>
          <a-button type="primary" v-print="'#printme'" v-has="'BisGameCoinRecordController:print'">{{$t('打印')}}</a-button>
          <a-button type="primary"  @click="handleValue" v-has="'BisAccountValueController:edit'">{{$t('运营设置')}}</a-button>
          <a-popover :title="$t('自定义列')" trigger="click" placement="bottom">
            <template slot="content">
              <a-checkbox-group
                @change="onColSettingsChange"
                v-model="settingColumns"
                :defaultValue="settingColumns"
              >
                <a-row style="width: 400px">
                  <template v-for="(item, i) in defColumns">
                    <template v-if="item.key != 'rowIndex' && item.dataIndex != 'action'">
                      <a-col :span="12" :key="i"
                        ><a-checkbox :value="item.dataIndex"
                          ><j-ellipsis :value="item.title" :length="10"></j-ellipsis></a-checkbox
                      ></a-col>
                    </template>
                  </template>
                </a-row>
              </a-checkbox-group>
            </template>
            <a-button type="setting">{{ $t('设置列') }}</a-button>
          </a-popover>
        </div>    
        <!-- table区域-begin -->
        <div id="printme">
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :scroll="{ x: true }"
            class="j-table-force-nowrap"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :customHeaderRow="customHeaderRow"
            :customRow="customRow"
            @change="handleTableChange"
          >
            <template slot="action" slot-scope="text, record">
              <a v-if="!record.gameId_dictText"></a>
              <a v-else @click.stop="machineReport(record)">{{$t('机位报表')}}</a>
            </template>
            <template slot="footer">
              <div style="font-weight: bold">
                <span>{{ totalInfo }}</span>
              </div>
            </template>
          </a-table>
        </div>
      </a-col>
    </a-row>

    <machine-report-modal ref="reportForm"></machine-report-modal>
    <account-value-modal ref="modalForm" @ok="modalFormOk"/>
  </a-card>
</template>

<script>
import Vue from 'vue'
import moment from 'moment'
import '@/assets/less/TableExpand.less'
import { getAction, downFile  } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import MachineReportModal from './modules/MachineReportModal'
import AccountValueModal from './modules/AccountValueModal'

export default {
  name: 'GameOperationReport',
  mixins: [JeecgListMixin],
  components: {
    MachineReportModal,
    AccountValueModal
  },
  data() {
    return {
      moment,
      description: '游戏机台运营报表页面',
      sortList: [],
      sortData: [],
      defaultSelectedKeys: [],
      selectedValues: [],
      treeItem: 0,
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      defColumns:[
        {
          title: this.$t('项目名称'),
          align: 'center',
          dataIndex: 'gameId_dictText',
          width: 247,
          customRender: (t, r) => {
            if(!t){
              return this.$t("合计")
            }
            return t
          },
        },
        {
          title: this.$t('支付金额'),
          align: 'center',
          dataIndex: 'payAmount',
          width: 100,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('投币'),
          align: 'center',
          dataIndex: 'memberCoin',
          width: 90,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('投A票'),
          align: 'center',
          dataIndex: 'memberAlottery',
          width: 90,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('投Z票'),
          align: 'center',
          dataIndex: 'memberZlottery',
          width: 90,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('投彩票'),
          align: 'center',
          dataIndex: 'memberLottery',
          width: 90,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('投实币'),
          align: 'center',
          dataIndex: 'physicalCoin',
          width: 90,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('总投币'),
          align: 'center',
          dataIndex: 'totalCoin',
          width: 90,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('退彩票'),
          align: 'center',
          dataIndex: 'outputLottery',
          width: 120,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('退A票'),
          align: 'center',
          dataIndex: 'outputAlottery',
          width: 120,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('退Z票'),
          align: 'center',
          dataIndex: 'outputZlottery',
          width: 120,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('退币'),
          align: 'center',
          dataIndex: 'outputCoin',
          width: 120,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('总退票'),
          align: 'center',
          dataIndex: 'outputValue',
          width: 120,
          customRender: function (t, r) {
            if(!t){
              t=0
            }
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('礼品名称'),
          align: 'center',
          dataIndex: 'outputGoodsId_dictText',
          width: 160,
        },
        {
          title: this.$t('退礼品数'),
          align: 'center',
          dataIndex: 'goodsNumber',
          width: 90,
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('投入金额'),
          align: 'center',
          dataIndex: 'inputPrice',
          width: 90,
          customRender: function (t, r) {
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('退出金额'),
          align: 'center',
          dataIndex: 'outputPrice',
          width: 100,
          customRender: function (t, r) {
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('毛利润'),
          align: 'center',
          dataIndex: 'profit',
          width: 90,
          customRender: function (t, r) {
            return t.toFixed(2)
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('毛利率'),
          align: 'center',
          dataIndex: 'profitRate',
          width: 120,
          customRender: function (t, r) {
            return t.toFixed(2)+"%"
          },
          customCell: function (t, r) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('操作'),
          align: 'center',
          dataIndex: 'action',
          width: 140,
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 表头
      columns: [],
      url: {
        list: '/game/bisGameCoinRecord/getReport',
        exportXlsUrl: '/game/bisGameCoinRecord/exportReportXls',
      },
      gameTypeList: [],
      queryParam: {
        createTime_begin: moment().format('YYYY-MM-DD 00:00:00'),
        createTime_end: moment().format('YYYY-MM-DD 23:59:59'),
        gameInfo: '',
        machineNo: '',
        shopCode: '',
        groupBy: 'game_type_id,game_id',
      },
      shops:[],
      tenantid: Vue.ls.get('TENANT_ID'),
      dataSources: [],
      isCustom:true,
      isHideData:false,
      hideCond: 1,
      //列设置
      settingColumns: [],
      totalCallback: this.totalCallbacks,
      total: {}
    }
  },
  created(){
    this.initColumns()
    this.getSortList()
  },
  mounted(){
    let that=this
    document.onkeydown = function(e) { 
      let key = window.event.keyCode; 
      if (key== 75 && event.ctrlKey) {
        window.event.preventDefault()
        that.isHideData = false
        that.queryParam.dataType=0
        that.searchQuery()
      }
    }
  },
  methods: {
    totalCallbacks(totalInfo) {
      this.total = totalInfo
      this.totalInfo = this.$t('合计')+':'
      this.columns.forEach(c=>{
        if(totalInfo[c.dataIndex]!==undefined){
          if(c.dataIndex == 'goodsNumber'){
            this.totalInfo += (' '+c.title+':'+totalInfo[c.dataIndex])
          }else if(c.dataIndex == 'profitRate'){
            this.totalInfo += (' '+c.title+':'+totalInfo[c.dataIndex].toFixed(2)+'%')
          }else{
            this.totalInfo += (' '+c.title+':'+totalInfo[c.dataIndex].toFixed(2))
          }
        }
      })
    },
    treeSelect(data) {
      this.selectedRowIndex = []
      this.selectedValues = data;
      this.queryParam.gameTypeId = data[0];
      this.searchQuery()
    },
    getSortList() {
      let that = this
      that.sortList = []
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'id'
      param.order = 'DESC'
      getAction('/game/bisGameType/rootList', param).then((res) => {
        if (res.success) {
          that.sortList = res.result.records
          if (that.sortList.length > 0) {
            that.sortList.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChildStore(col)
              }
            })
            that.sortData = that.getDataByResult(that.sortList);
            that.sortData.unshift({ key: '', id: '', title: that.$t('全部') });
            that.defaultSelectedKeys.push(that.sortData[0].key);
            that.selectedValues = [...that.defaultSelectedKeys];
            that.queryParam.gameTypeId = that.selectedValues[0];
            that.customInit();
          }
        }
      })
    },
    getHasChildStore(store) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = store.id
      getAction('/game/bisGameType/rootList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChildStore(col)
              }
            })
            store.children = that.getDataByResult(res.result.records)
            that.sortData = [...that.sortData]
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    getDataByResult(result) {
      return result.map((item) => {
        return item
      })
    },
    customRow(r, i){
      return {
        on: {
          click: () => {
            let x = this.selectedRowIndex.findIndex(r=>{return r=='a'+this.ipagination.current+''+i})
            if( x == -1 ){
              this.selectedRowIndex.push('a'+this.ipagination.current+''+i)
            }else{
              this.selectedRowIndex.splice(x, 1)
            }
          }
        },
        style: {
          whiteSpace: 'break-spaces',
          wordBreak: 'break-word',
          overflowWrap: 'break-word',
          backgroundColor: this.selectedRowIndex.findIndex(r=>{return r=='a'+this.ipagination.current+''+i}) > -1 ? '#FFECE6' : '',
          fontWeight: !r.gameId_dictText ? 700 : 400,
        }
      }
    },
    initDictConfig() {
      this.customInit()
      initDictOptions('bis_shop,name,code').then((res) => {
        if (res.success) {
          this.shops = res.result
          this.shops.unshift({ value: '', title: this.$t('全部') })
        }
      })
    },
    handleValue(){
      this.$refs.modalForm.show();
    },
    customInit(){
      this.isHideData = true
      this.queryParam.dataType=1
      this.searchQuery()
    },
    searchReset(){
      this.queryParam = {
        createTime_begin: moment().format('YYYY-MM-DD 00:00:00'),
        createTime_end: moment().format('YYYY-MM-DD 23:59:59'),
        gameInfo: '',
        shopCode: '',
        groupBy: 'game_type_id,game_id',
      }
      this.selectedValues = [...this.defaultSelectedKeys];
      this.$forceUpdate()
      this.queryParam.gameTypeId = this.selectedValues[0];
      this.customInit()
    },
    machineReport(record) {
      record.createTime_begin = this.queryParam.createTime_begin
      record.createTime_end = this.queryParam.createTime_end
      record.hideColumns = this.getColumnField('columns','defColumns')
      this.$refs.reportForm.show(record, this.columns)
    },
    handleDateClick(evt){
      if(evt.key=='1'){
        this.queryParam.createTime_begin=moment().format('YYYY-MM-DD 00:00:00')
        this.queryParam.createTime_end=moment().format('YYYY-MM-DD 23:59:59')
      }
      if(evt.key=='2'){
        this.queryParam.createTime_begin=moment().subtract(2,'day').format('YYYY-MM-DD 00:00:00')
        this.queryParam.createTime_end=moment().format('YYYY-MM-DD 23:59:59')
      }
      if(evt.key=='3'){
        this.queryParam.createTime_begin=moment().subtract(6,'day').format('YYYY-MM-DD 00:00:00')
        this.queryParam.createTime_end=moment().format('YYYY-MM-DD 23:59:59')
      }
      if(evt.key=='4'){
        this.queryParam.createTime_begin=moment().subtract(1, 'month').format('YYYY-MM-DD 00:00:00')
        this.queryParam.createTime_end=moment().format('YYYY-MM-DD 23:59:59')
      }
      if(evt.key=='5'){
        this.queryParam.createTime_begin=moment().subtract(3,'month').format('YYYY-MM-DD 00:00:00')
        this.queryParam.createTime_end=moment().format('YYYY-MM-DD 23:59:59')
      }
      if(evt.key=='6'){
        this.queryParam.createTime_begin=moment().subtract(6,'month').format('YYYY-MM-DD 00:00:00')
        this.queryParam.createTime_end=moment().format('YYYY-MM-DD 23:59:59')
      }
      if(evt.key=='7'){
        this.queryParam.createTime_begin=moment().startOf('year').format('YYYY-MM-DD 00:00:00')
        this.queryParam.createTime_end=moment().format('YYYY-MM-DD 23:59:59')
      }
      this.searchQuery()
    },
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ':colsettings'
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter((item) => {
        if (item.key == 'rowIndex' || item.dataIndex == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })
      this.columns = cols
      this.totalCallbacks(this.total)
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
      var key = this.$route.name + ':colsettings'
      let colSettings = Vue.ls.get(key)
      let arr = ['memberZlottery','memberAlottery','memberLottery','outputCoin','outputAlottery','outputZlottery', 'outputLottery']
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = [], settingColumns = [], columns = []
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex)
          if(arr.indexOf(item.dataIndex)==-1){
            settingColumns.push(item.dataIndex)
            columns.push(item)
          }
        })
        this.settingColumns = settingColumns
        this.columns = columns
      } else {
        this.settingColumns = colSettings
        const cols = this.defColumns.filter((item) => {
          if (item.key == 'rowIndex' || item.dataIndex == 'action') {
            return true
          }
          if (colSettings.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns = cols
      }
    },
    handleExportXls(fileName) {
      this.exloading = true
      if (!fileName || typeof fileName != "string") {
        fileName = this.$t('导出文件')
      }
      let param = this.getQueryParams();
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(",")
      }
      param.hideColumns = this.getColumnField('columns','defColumns')
      console.log("导出参数", param)
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning(this.$t('文件下载失败'))
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      }).finally(() => {
        this.exloading = false
      })
    },
    getColumnField(key,dkey){
      let arr=[],str=''
      this[dkey].forEach(dk=>{
        let x= this[key].findIndex(k=>{
          return dk.dataIndex==k.dataIndex
        })
        if(x==-1){
          arr.push(dk)
        }
      })
      str=arr.map(a=>{return a.dataIndex}).join(',')
      return str
    }
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>